package org.wupuser.config.intercepter;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.wupuser.util.JWTTokenUtil;

@Component
public class TokenInterceptor implements HandlerInterceptor {
	@Override
	public boolean preHandle(
		HttpServletRequest request,
		HttpServletResponse response,
		Object handler) throws Exception {
		String token = request.getHeader("Authorization");
		String body = request.getHeader("Key");
		if (token == null) {
			response.setStatus(401);
			response.getWriter()
				.write("未设置token");
			return false;
		}
		
		token = token.substring(7); // Bearer token
		
		Boolean result = JWTTokenUtil.validateToken(
			token,
			body);
		
		if (! result) {
			response.setStatus(401);
			response.getWriter()
				.write("token无效，请重新登录");
		}
		return result;
	}
}
